using MediatR;
using RBAC.Domain.ProductionPlans;
using RBAC.ErrorCode;
using RBAC.Read.Api.Application.Command.ProductionPlans;
using RBAC.Interstructrue.Base;
using Dapper;

namespace RBAC.Read.Api.Application.Handler.ProductionPlans
{
    public class GetGoodsInfoCommandHandler : IRequestHandler<GetGoodsInfoCommands, APIResult<APIPaging<GoodsInfo>>>
    {
        private readonly IBaseRepository<GoodsInfo> goodsRep;

        public GetGoodsInfoCommandHandler(IBaseRepository<GoodsInfo> goodsRep)
        {
            this.goodsRep = goodsRep;
        }

        public Task<APIResult<APIPaging<GoodsInfo>>> Handle(GetGoodsInfoCommands request, CancellationToken cancellationToken)
        {
            try
            {
                var pageIndex = request.PageIndex <= 0 ? 1 : request.PageIndex;
                var pageSize = request.PageSize <= 0 ? 10 : request.PageSize;

                var where = "IsDeleted = false";
                var param = new DynamicParameters();

                if (!string.IsNullOrWhiteSpace(request.GoodNumber))
                {
                    where += " AND GoodNumber LIKE @GoodNumber";
                    param.Add("GoodNumber", $"%{request.GoodNumber}%");
                }
                if (!string.IsNullOrWhiteSpace(request.GoodName))
                {
                    where += " AND GoodName LIKE @GoodName";
                    param.Add("GoodName", $"%{request.GoodName}%");
                }
                if (!string.IsNullOrWhiteSpace(request.GoodType))
                {
                    where += " AND GoodType LIKE @GoodType";
                    param.Add("GoodType", $"%{request.GoodType}%");
                }

                var orderBy = "Id DESC";
                var (data, total) = goodsRep.GetPaged(pageIndex, pageSize, where, orderBy, param);

                var paging = new APIPaging<GoodsInfo>
                {
                    PageDatas = data,
                    TotalCount = total
                };

                return Task.FromResult(new APIResult<APIPaging<GoodsInfo>>
                {
                    Code = APIEnums.Success,
                    Msg = "查询成功",
                    Data = paging
                });
            }
            catch (Exception ex)
            {
                return Task.FromResult(new APIResult<APIPaging<GoodsInfo>>
                {
                    Code = APIEnums.Fail,
                    Msg = "查询失败：" + ex.Message,
                    Data = new APIPaging<GoodsInfo>()
                });
            }
        }
    }
}
